import { getNotifyRecordList, readNotifyRecord } from "@/api/modules/notification";
import DialogBox from "@/components/DialogBox";
import MsgTypeTag from "@/components/Tags/MsgTypeTag";
import { showTips } from "@/utils/util";
import NotifyDetail from "@/views/iot/notify/components/notifyDetail";
import { dayjs } from "element-plus";
export default defineComponent({
	emits: ["refresh"],
	setup(props, { emit }) {
		const currentItem = ref({});
		//打开详情
		const handerBtn = (item: any) => {
			currentItem.value = item;
			detailDialog.visible = true;
		};
		const detailDialog = reactive({ visible: false, title: "通知详情" });
		const state = reactive<any>({
			params: {
				pageIndex: 1,
				pageSize: 7,
				readStatus: 1
			},
			list: [],
			total: 0
		});
		//切换分页
		const handleSizeChange = (val: number) => {
			state.params.pageIndex = val;
			getList();
		};
		onMounted(() => {
			getList();
		});
		//获取通知列表数据
		const getList = async () => {
			let { result } = await getNotifyRecordList(state.params);
			state.list = result.records || [];
			state.total = result.total || 0;
		};
		const read = async (id: string) => {
			let { code, message } = await readNotifyRecord({ id });
			let ok = showTips(code, "消息已读", message);
			if (ok) {
				state.params.pageIndex = 1;
				getList();
				emit("refresh");
			}
		};
		const assContent = (val: any, item?: any) => {
			let content = val.email || val.sms || val.message + val.sn || "";
			return (
				<div>
					{content.split(",告警类型:")[0].split("，告警时间：")[0].split("告警级别：")[0] || "暂无更多消息"}
					<span class="cursor-pointer primary-color" onClick={() => handerBtn(item)}>
						（详情）
					</span>
				</div>
			);
		};
		return () => {
			return (
				<div class="header-message-panel">
					<DialogBox title={detailDialog.title} width="800px" v-model:visible={detailDialog.visible} footerLabel={["关闭"]}>
						<NotifyDetail detail={currentItem.value}></NotifyDetail>
					</DialogBox>
					<div class="divide-y divide-solid divide-black divide-opacity-20">
						{state.list.map((item: any) => {
							return (
								<div class="border-l-0 border-r-0">
									<div class="flex header-message-item-footer justify-between p-2 bg-gray-100 text-gray-400">
										<div>
											<MsgTypeTag content={item.content} />
											<span>{dayjs(item.createTime).format("YYYY-MM-DD HH:mm:ss")}</span>
										</div>
										<div>
											<el-link type="primary" onClick={() => read(item.id)}>
												标记已读
											</el-link>
										</div>
									</div>
									<div class="mle header-message-item-content">
										{assContent((item.content && JSON.parse(item.content)[0]) || {}, item)}
									</div>
								</div>
							);
						})}
					</div>
					<el-pagination
						class="mt-2"
						small
						background
						layout="prev, pager, next"
						pageSize={state.params.pageSize}
						total={state.total}
						onCurrentChange={handleSizeChange}
					/>
				</div>
			);
		};
	}
});
